package com.iocup.keybastion.spring.starter.config;


import com.iocup.keybastion.authorize.parser.AuthAnnoObject;
import com.iocup.keybastion.authorize.parser.AuthAnnotationParser;
import com.iocup.keybastion.utils.NameUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Description: 解析bean中的权限注解，放入缓存中
 * @Author: xyjxust
 * @Date: 2022/3/8 11:32
 */
public class AuthAnnotationParserProcessor implements BeanPostProcessor {

    @Autowired
    private AuthAnnotationParser authAnnotationParser;


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Annotation[] annotations = bean.getClass().getAnnotations();
        AuthAnnoObject authAnnoObject =null;
        if (annotations != null && annotations.length > 0) {
            for (Annotation annotation : annotations) {
                 authAnnoObject = authAnnotationParser.getAuthAnnoObject(annotation.annotationType());
                if (authAnnoObject != null) {
                    this.authAnnotationParser.parser(bean.getClass().getName(),authAnnoObject,annotation);
                }
            }
        }
        Method[] methods =   ReflectionUtils.getAllDeclaredMethods(bean.getClass());
        if(methods!=null&&methods.length>0){
            for(Method method:methods){
                annotations = method.getAnnotations();
                if (annotations != null && annotations.length > 0) {
                    for (Annotation annotation1 : annotations) {
                        authAnnoObject = authAnnotationParser.getAuthAnnoObject(annotation1.annotationType());
                        if (authAnnoObject != null) {
                            authAnnotationParser.parser(NameUtils.buildMethodFullPath(method),  authAnnoObject, annotation1);
                        }
                    }
                }
            }
        }
        return bean;
    }

}
